package com.dstats.fragments;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ProgressBar;

import com.adapter.RedditAdapter;
import com.dstats.R;
import com.entities.Reddit;
import com.fetch.Fetch;

public class RedditFragment extends Fragment {
	
	@Override
	public void onResume() {
		super.onResume();
		new FetchReddit().execute();
	}
	
	private ExpandableListView listView;
	private ProgressBar progressBarReddit;
	private void setAdapterAndListener(List<Reddit> list){
		if(list!=null){
		RedditAdapter reddit = new RedditAdapter(getActivity(), list);
		listView.invalidate();
		listView.setAdapter(reddit);
		}
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.expandable_listview, container, false);
		listView = (ExpandableListView) rootView.findViewById(R.id.expandableListView);
		progressBarReddit = (ProgressBar) rootView.findViewById(R.id.progressBarReddit);
		setAdapterAndListener(Reddit.redditList);
		if(Reddit.redditList==null){
			new FetchReddit().execute();
			
		}
		return rootView;
	}
	
	class FetchReddit extends Fetch {

		@Override
		protected void onPreExecute() {
		
			super.onPreExecute();
			progressBarReddit.setVisibility(View.VISIBLE);
			progressBarReddit.setIndeterminate(true);
		}
		
		@Override
		protected List<NameValuePair> getParams() {
			
			return new ArrayList<NameValuePair>();
		}

		@Override
		protected String getUrl() {
			return Reddit.JSON_URL;
		}
		
		@Override
		protected void onPostExecute(final JSONObject result) {
			
			super.onPostExecute(result);
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					
					setAdapterAndListener(Reddit.getWhatIsHot(result));
					progressBarReddit.setVisibility(View.INVISIBLE);
				}
			});
		}
		
	}
}
